import * as React from 'react';
import Link from '@mui/material/Link';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Title from '../home/Title';
import { useEffect } from 'react';
import { addUser, getUserList } from '../../../api/user';

import TextField from '@mui/material/TextField';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';

import { toast } from 'react-toastify';


// 用户名正则，4到16位（字母，数字
const uPattern = /^[a-zA-Z0-9]{4,16}$/

const UserAdd = () => {


    const handleSubmit = async (event) => {
        event.preventDefault()
        const data = new FormData(event.currentTarget)
        let username = data.get('username')
        let password = data.get('password')

        if(!username || !password || username.trim().length ===0 || password.trim().length ===0 ) {
            // alert(`请输入用户名和密码！`)

            toast.error(`请输入用户名和密码！`)
            return
        }

        if(!uPattern.test(username)) {
            // alert(`用户名4到16位(字母或数字)`)

            toast.error(`用户名4到16位(字母或数字)`)
            return
        }
        
        let res = await addUser(username, password)
        if(res && res.id) {
            // alert(`创建账号成功！`)

            toast.info(`用户名4到16位(字母或数字)`)
            window.location.reload()
        }
    }


    return (
        <div>

            <Box component="form" noValidate onSubmit={handleSubmit} sx={{ mt: 1 }}  autoComplete="off">
                {/* <input type="password" style={{position: 'absolute', top: '-999px'}}/> */}
                <TextField
                    margin="normal"
                    required
                    fullWidth
                    id="username"
                    label="用户名"
                    name="username"
                    autoComplete="new-password"
                    autoFocus
                />
                <TextField
                    margin="normal"
                    required
                    fullWidth
                    name="password"
                    label="密码"
                    type="password"
                    id="password"
                    autoComplete="new-password"
                />


                <Button
                    type="submit"
                    fullWidth
                    variant="contained"
                    sx={{ mt: 3, mb: 2 }}
                >
                    创建账号
                </Button>
            </Box>

        </div>
    )
}

export default UserAdd




